package org.ms.springboot.aop;

import lombok.extern.slf4j.Slf4j;
import org.ms.springboot.aop.exception.CheckException;
import org.ms.springboot.aop.model.Girl;
import org.ms.springboot.aop.model.ResultMessage;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Slf4j
@RestController
public class AopDemoController {

    @RequestMapping("hello")
    public String hello(String name) {
        log.info("input hello");
        return "OK: " + name;
    }

    @RequestMapping("girl")
    public ResultMessage girl(@Valid Girl girl, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new ResultMessage(1, bindingResult.getFieldError().getDefaultMessage(), null);
        }

        if (girl.getAge() > 100) {
            throw new CheckException(100, "年龄不能超过100");
        }

        if (girl.getAge() > 200) {
            throw new CheckException(101, "年龄必须小于200");
        }

        return new ResultMessage(0, "成功", girl);
    }

}
